import requests
import pandas as pd
import time

# 设置关键词
keyword = '航拍美景'

# 设置请求头信息
headers = {
    'Accept-Language': 'zh-CN,zh;q=0.9',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36'
}

# 给出接口地址
url = 'https://image.baidu.com/search/acjson'

# 初始化动态参数
rn = 30
params = {
    'tn': 'resultjson_com',
    'ipn': 'rj',
    'ct': '201326592',
    'fp': 'result',
    'word': keyword,
    'queryWord': keyword,
    'pn': 0,
    'rn': rn
}

# 循环请求3次数据
data_list = []
for page in range(1, 4):
    # 更改参数pn的值
    params['pn'] = (page - 1) * rn
    # 发起请求，获取JSON格式数据
    response = requests.get(url=url, params=params, headers=headers)
    json_data = response.json()
    data = json_data['data'][:-1]
    # 提取图片数据
    for item in data:
        image_url = item['replaceUrl'][0]['ObjUrl']
        image_type = item['type']
        data_list.append([image_url, image_type])
    # 适当暂停，以免触发反爬
    time.sleep(3)

# 整理和导出数据
df = pd.DataFrame(data_list, columns=['图片网址', '图片类型'])
df.to_csv(f'图片_{keyword}.csv', index=False, encoding='utf-8-sig')
